<?php

namespace Admin\Controller;

use User\Api\UserApi;
use Org\Util\Sync;
use Think\Model;
use Org\Util\Rest;
use Org\BMap; 

/**
 * 订单控制器
 * @author zhangwei
 * 2015-06-17
 */
class OrderController extends AdminController {
    /**
     * 订单列表
     * @author zhangwei
     * 2015-06-17
     */
    public function index() {
        $areaList = M("area")->select();
        $data['areaList'] = $areaList;
        $this->data = $data;
        $id = I('id');
        $phone = I('user_phone');
        $name = I('user_name');
        $street = I('street');
        $shop = I('shop');
        $aid = I('aid');
        $status = I('status');
        $isExport = I('isExport');
        $b_date = I('b_date');
        $e_date = I('e_date');
        //$sql = "select * from gr_order where 1=1";
        if ($id) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $map['orderid']=array('like','%'.$id.'%');
        }
        if ($phone) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $map['toPhone']=array('like','%'.$phone.'%');
        }
        if ($name) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $map['toName']=array('like','%'.$name.'%');
        }
        if ($street) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $map['toStreet']=array('like','%'.$street.'%');
        }
        if ($shop) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $map['toShopName']=array('like','%'.$shop.'%');
        }

        if ($status != null && $status != 0) {
            //$sql .= " and gr_order.status = '" . $status . "'";
            $map['status']=$status;
        }
        if ($isExport != null && $isExport != 3) {
            $map['is_export']=$isExport;
        }
        if ($b_date && $e_date) {
            //$sql .= " and gr_order.createDate >= " . strtotime($b_date);
            $map['createDate']=array('between',array(strtotime($b_date),strtotime($e_date)));
        }else if($b_date){
            $map['createDate']=array('egt',strtotime($b_date));
        }else if($e_date) {
            //$sql .= " and gr_order.createDate <= " . strtotime($e_date);
            $map['createDate']=array('elt',strtotime($e_date));
        }

        $list = $this->listsM('order', $map,'createDate desc');
        sg_int_to_string_order($list);
        //自动订单确认 start
        $vaildTime=time()-3*24*3600;
//        $vaildTime=time();
        $map2['status']=2000;
        $map2['createDate']= array('lt',$vaildTime);
        $autoSuccessLists=D('order')->where($map2)->select();
        for($i=0;$i<count($autoSuccessLists);$i++){
            $this->ajaxOrderSuccess($autoSuccessLists[$i]["orderid"],1);
        }
        //end
        $this->assign('_list', $list);
        $this->assign('_aid', $aid);
        $this->assign('_status', $status);
        $this->assign('_isExport', $isExport);
        $this->display();
    }
    /**
     * 触发确认订单
     * @param $orderid string 订单号
     * @author Scor 2015-10-12
     */
    public function ajaxOrderSuccess($orderid,$mark=""){
        $data['orderid']=$orderid;
        $orderStatus['status']=3000;
        D('order')->where($data)->save($orderStatus);

        if($mark>0){
        }else{
            $this->success("确认成功");
        }
    }
    /**
     * 拒收处理
     * @author Scor 2015-10-11
     */
    public function refuseAction(){
        $map['orderid']=I('orderid');
        $oldOrder=D('order')->where($map)->find();
        $data2['amount']=I('amount')-$oldOrder['useamount'];
        D('order')->where($map)->save($data2);
        $cartnum=I('cartnum');
        $mark=I('mark');
        $totalprice=I('totalprice');
        $pid=I('pid');
        $DB =D('order_goods');
        for($i=0;$i<count($totalprice);$i++){
            $map['pid']=$pid[$i];
            $data['cartnum']=$cartnum[$i];
            $data['totalprice']=$totalprice[$i];
            $data['remark']=$mark[$i];
            $DB->where($map)->save($data);
        }
            $this->success("修改成功!", U('Order/orderdetails?orderid='.$map['orderid']),1);

    }
    /**
     * 订单详情
     * @author zhangwei
     * 2015-06-18
     */
    public function Orderdetails($orderid = null) {
        $map['orderid'] = $orderid;
        $orderlist = D('Order')->where($map)->select();
        sg_int_to_string_order($orderlist);
        $order = $orderlist[0];
        $order['order_goods'] =D('oderder')->query("select b.name pname,b.quantity,b.price pprice,a.* from gr_order_goods a,gr_product b where  a.pid = b.id and a.orderid = '".$map['orderid']."'");
//        $order['order_goods'] = M('order_goods')->where($map['orderid'])->select(); 
        $this->order = $order;
        $this->display();
    }
    /**
     * 取消交易
     * @param $orderid string 订单号
     * @author Scor 2015-10-1
     */
    public function ajaxOrderCancel($orderid){
        $data['orderid']=$orderid;
        $data['status']=array(array('gt',0),array('lt',3000), 'and') ;
        $goodsTable=D('product');
        $res=D('order_goods')->where($data)->select();
        foreach ($res as $value){
            $data2['id']=$value['pid'];
            $goodsTable->where($data2)->setInc('inventory',$value['cartnum']);
        }
        $orderInfo=M("order")->where($data)->find();
        $map['id']=$orderInfo['uid'];
        if($orderInfo['useamount']>0){
            $changeAmount=$orderInfo['useamount'];
            $detail="平台撤销".$orderid;
            $this->amountFlow($orderInfo['uid'],$changeAmount,"incre",$detail);
            D('buyers')->where($map)->setInc('amount',$changeAmount);
        }
        $orderStatus['status']=4000;
        $data3['nickname']=get_nickname();
        $mark="取消".$orderInfo['toName']."的订单".$orderid;
        $data3['action']=$mark;
        $data3['objectuid']=$orderInfo['uid'];
        $data3['creattime']=time();
        D('action_flow')->data($data3)->add();
        $limitTable = M("product_limit");
        $limitTable->where(array('orderid'=>$orderid))->delete();
        if(D('order')->where($data)->save($orderStatus)){
             $this->success("交易取消成功");
        }
    }
    /**
     * 受理订单
     * @param $orderid string 订单号
     * @author Scor 2015-10-1
     */
    public function ajaxOrderTaken($orderid){
        $data['orderid']=$orderid;
        $orderStatus['status']=2000;
        if(D('order')->where($data)->save($orderStatus)){
             $this->success("订单受理成功");
        }else{
            $this->error("订单受理失败");
        }
    }
    /**
     * 订单导出
     * @author Scor
     * 2015-06-18
     */
    public function orderExport() {
        $sql = " select orderid,case status "
                . "when 1000 then '已下单，未受理'"
                . "when 2000 then '已受理，未交易成功'"
                . "when 3000 then '交易成功'"
                . "when 4000 then '平台取消交易'"
                . "when -1 then '用户取消交易'"
                . "end as status,"
                ."(select c.sname from gr_relationship c where a.uid = c.uid),"
                . "amount,useamount,toName,toPhone,toStreet,toShopName,from_unixtime(createDate),remark ,
                (select b.goods1 from gr_vorder_goods2 b where a.orderid = b.orderid)
                goods from gr_order a where 1=1 ";
        $id = I('id');
        $phone = I('user_phone');
        $name = I('user_name');
        $street = I('street');
        $shop = I('shop');
        $status = I('status');
        $isExport = I('isExport');
        $b_date = I('b_date');
        $e_date = I('e_date');
        if ($id) {
            $sql .= " and a.orderid like '%" . $id . "%'";
        }
        if ($phone) {
            $sql .= " and a.toPhone like '%" . $phone . "%'";
        }
        if ($name) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $sql .= " and a.toName like '%" . $name . "%'";

        }
        if ($street) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $sql .= " and a.toStreet like '%" . $street . "%'";

        }
        if ($shop) {
            //$sql .= " and gr_order.orderid like '%" . $id . "%'";
            $sql .= " and a.toShopName like '%" . $shop . "%'";

        }
        if ($status) {
            //$sql .= " and gr_order.status = '" . $status . "'";
            $sql .= " and a.status = " . $status;
        }
        if($isExport!=null&&$isExport!=""){
            $sql .= " and a.is_export = " . $isExport;
        }
        if ($b_date) {
            $sql .= " and a.createDate >= " . strtotime($b_date);
        }
        if ($e_date) {
            $sql .= " and a.createDate <= " . strtotime($e_date);
        }
        $Model = new Model();
        $data = $Model->query($sql);
        if ($data) {
            $orderTable = M('order');
            $data1 = array('is_export' => 1);

            $args = array_map(function($src){
                return $src['orderid'];}, $data);
            $map['orderid']  = array('in',$args);
            $result = $orderTable->where($map)->setField($data1);
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";
            $headArr = array("订单编号","订单状态","业务员","成交金额","余额支付","收货人","联系方式","收货地址","店铺名","下单时间","备注","商品");
            $this->getExcel($filename, $headArr, $data,null);
        }else{
            $this->error("没有可导出的数据");
        }
    }
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);
        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $objPHPExcel->getActiveSheet()->getStyle($colum . '2')->getFont()->setBold(true);
            $key += 1;
        }
        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
        $objActSheet->getColumnDimension('A')->setWidth(18);
        $objActSheet->getColumnDimension('B')->setWidth(16);
        $objActSheet->getColumnDimension('C')->setWidth(10);
        $objActSheet->getColumnDimension('D')->setWidth(10);
        $objActSheet->getColumnDimension('E')->setWidth(15);
        $objActSheet->getColumnDimension('F')->setWidth(20);
        $objActSheet->getColumnDimension('G')->setWidth(20);
        $objActSheet->getColumnDimension('H')->setWidth(20);
        $objActSheet->getColumnDimension('I')->setWidth(40);
        $objActSheet->getColumnDimension('J')->setWidth(60);
        $objActSheet->getColumnDimension('K')->setWidth(80);
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

}
